package com.ysstech.common.util.fileutil;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.csource.common.NameValuePair;
import org.csource.fastdfs.*;
import org.springframework.core.io.ClassPathResource;

/**
 * 文件上传
 */
@Slf4j
public class FastDFSClient {
    private static TrackerClient trackerClient;
    private static final String FDFS_CLIENT_DEFAULT = "fdfs_client.conf";
    static {
        try {
            ClassPathResource resource = new ClassPathResource(FDFS_CLIENT_DEFAULT);
            if (null != resource) {
                ClientGlobal.init(resource.getPath());
                TrackerGroup trackerGroup = ClientGlobal.g_tracker_group;
                trackerClient = new TrackerClient(trackerGroup);
            } else {
                log.error("获取配置文件出错！");
            }
        } catch (Exception e) {
            log.error("FastDFS Client Init Fail!", e);
        }
    }

    /**
     * <B>方法名称：</B>删除方法<BR>
     * <B>概要说明：</B>根据id来删除一个文件<BR>
     *
     * @param fileId 文件id
     * @return 删除成功返回0，非0则操作失败，返回错误代码
     */
    public static int delete(String groupName, String fileId) throws Exception {
        log.info("删除服务器文件开始");
        TrackerServer trackerServer = null;
        StorageServer storageServer = null;
        StorageClient1 storageClient1 = null;
        int code = -1;
        try {
            trackerServer = trackerClient.getConnection();
            storageServer = trackerClient.getStoreStorage(trackerServer, groupName);
            storageClient1 = new StorageClient1(trackerServer, storageServer);
            code = storageClient1.delete_file1(fileId);
            log.info("删除服务器文件结束");
        } catch (Exception ex) {
            log.error(ex.toString());
            throw new Exception("删除服务器文件失败，请稍后重试！");
        } finally {
            try {
                storageServer.close();
                trackerServer.close();
            } catch (IOException e) {
                log.error(e.toString());
                throw new Exception("删除服务器文件失败，请稍后重试！");
            }
        }
        return code;
    }

    /**
     * <B>方法名称：</B>删除方法<BR>
     * <B>概要说明：</B>根据id来删除一个文件<BR>
     *
     * @param fileId 文件id
     * @return 删除成功返回0，非0则操作失败，返回错误代码
     */
    public static int delete(String fileId) throws Exception {
        int code = -1;
        try {
            Matcher matcher = Pattern.compile("/").matcher(fileId);
            if (!matcher.find()) {
                return code;
            }
            String groupName = fileId.substring(0, matcher.start()).trim();
            code = delete(groupName, fileId);
            return code;
        } catch (Exception ex) {
            log.error(ex.toString());
            throw new Exception("下載服务器文件失败，请稍后重试！");
        }
    }


    /**
     * <B>方法名称：</B>下载方法<BR>
     * <B>概要说明：</B>通过文件id进行下载<BR>
     *
     * @param fileId 文件id
     * @return 返回InputStream
     */
    public static InputStream download(String groupName, String fileId) throws Exception {
        TrackerServer trackerServer = null;
        StorageServer storageServer = null;
        StorageClient1 storageClient1 = null;
        try {
            trackerServer = trackerClient.getConnection();
            storageServer = trackerClient.getStoreStorage(trackerServer, groupName);
            storageClient1 = new StorageClient1(trackerServer, storageServer);
            byte[] bytes = storageClient1.download_file1(fileId);
            InputStream inputStream = new ByteArrayInputStream(bytes);
            return inputStream;
        } catch (Exception ex) {
            log.error(ex.toString());
            throw new Exception("下載服务器文件失败，请稍后重试！");
        } finally {
            try {
                storageServer.close();
                trackerServer.close();
            } catch (IOException e) {
                log.error(e.toString());
                throw new Exception("下載服务器文件失败，请稍后重试！");
            }
        }
    }

    /**
     * <B>方法名称：</B>下载方法<BR>
     * <B>概要说明：</B>通过文件id进行下载<BR>
     *
     * @param fileId 文件id
     * @return 返回InputStream
     */
    public static InputStream download(String fileId) throws Exception {
        try {
            Matcher matcher = Pattern.compile("/").matcher(fileId);
            if (!matcher.find()) {
                return null;
            }
            String groupName = fileId.substring(0, matcher.start()).trim();
            InputStream inputStream = download(groupName, fileId);
            return inputStream;
        } catch (Exception ex) {
            log.error(ex.toString());
            throw new Exception("下載服务器文件失败，请稍后重试！");
        }
    }

    /**
     * <B>方法名称：</B><BR>
     * <B>概要说明：</B><BR>
     *
     * @param oldFileId 旧文件id  只是id 不带完整路径
     * @param file      新文件
     * @return 上传成功返回id，失败返回null
     */
    public static String uploadFile(File file, String oldFileId) throws Exception {
        String path = "";
        try {
            // 先上传
            path = upload(file);
            if (StringUtils.isBlank(oldFileId)) {
                return path;
            }
            // 再删除
            delete(oldFileId);
        } catch (Exception ex) {
            log.error(ex.toString());
            throw new Exception("上传失败失败，请稍后重试！");
        }
        return path;
    }

    /**
     * <B>方法名称：</B><BR>
     * <B>概要说明：</B><BR>
     *
     * @param oldImageId 旧文件id 带完整路径，图片每次反显
     * @param file       新文件
     * @return 上传成功返回id，失败返回null
     */
    public static String uploadImage(File file, String oldImageId) throws Exception {
        String path = "";
        try {
            // 先上传
            String host = gethost();
            path = host + upload(file);
            if (StringUtils.isBlank(oldImageId)) {   // 再删除
                return path;
            }
            oldImageId = oldImageId.substring(host.length(), oldImageId.length()); //截取掉host
            delete(oldImageId);
        } catch (Exception ex) {
            log.error(ex.toString());
            throw new Exception("上传失败失败，请稍后重试！");
        }
        return path;
    }

    /**
     * <B>方法名称：</B>上传方法<BR>
     * <B>概要说明：</B><BR>
     *
     * @param file 文件
     * @return 上传成功返回id，失败返回null
     */
    public static String upload(File file) throws Exception {
        log.info("开始上传文件");
        TrackerServer trackerServer = null;
        StorageServer storageServer = null;
        StorageClient1 storageClient1 = null;
        FileInputStream fis = null;
        String fileid = "";
        try {
            NameValuePair[] meta_list = null; // new NameValuePair[0];
            fis = new FileInputStream(file);
            byte[] file_buff = null;
            if (fis != null) {
                int len = fis.available();
                file_buff = new byte[len];
                fis.read(file_buff);
            }
            trackerServer = trackerClient.getConnection();
            String fileName = file.getName();
            String ext = fileName.substring(fileName.lastIndexOf(".") + 1);
            storageServer = trackerClient.getStoreStorage(trackerServer);
            storageClient1 = new StorageClient1(trackerServer, storageServer);
            fileid = storageClient1.upload_file1(file_buff, ext, meta_list);
            log.info("上传文件结束" + fileid);
        } catch (Exception ex) {
            log.error(ex.toString());
            throw new Exception("上传失败，请稍后重试！");
        } finally {
            try {
                fis.close();
                storageServer.close();
                trackerServer.close();
            } catch (IOException e) {
                log.error(e.toString());
                throw new Exception("上传失败，请稍后重试！");
            }

        }
        return fileid;
    }

    /**
     * 获取文件服务器访问路径
     *
     * @return
     * @throws Exception
     */
    public static String gethost() throws Exception {
        TrackerServer trackerServer = null;
        String path = "";
        try {
            trackerServer = trackerClient.getConnection();
            path = "http://" + trackerServer.getInetSocketAddress().getHostString()
                    + ":" + ClientGlobal.getG_tracker_http_port() + "/";
        } catch (Exception ex) {
            log.error(ex.toString());
            throw new Exception("上传失败，请稍后重试！");
        } finally {
            try {
                trackerServer.close();
            } catch (IOException e) {
                throw new Exception("上传失败，请稍后重试！");
            }
        }

        return path;
    }

    /**
     * <B>方法名称：</B>上传方法<BR>
     * <B>概要说明：</B><BR>
     *
     * @param data 数据
     * @return 上传成功返回id，失败返回null
     */
    public static String upload(byte[] data, String extName) throws Exception {
        log.info("开始上传文件");
        TrackerServer trackerServer = null;
        StorageServer storageServer = null;
        StorageClient1 storageClient1 = null;
        String fileid = "";
        try {
            NameValuePair[] meta_list = null; // new NameValuePair[0];
            trackerServer = trackerClient.getConnection();
            storageServer = trackerClient.getStoreStorage(trackerServer);
            storageClient1 = new StorageClient1(trackerServer, storageServer);
            fileid = storageClient1.upload_file1(data, extName, meta_list);
            log.info("上传文件结束");
        } catch (Exception ex) {
            log.error(ex.toString());
            throw new Exception("上传失败失败，请稍后重试！");
        } finally {
            try {
                storageServer.close();
                trackerServer.close();
            } catch (IOException ex) {
                throw new Exception("上传失败失败，请稍后重试！");
            }
        }
        return fileid;
    }


    /**
     * 上传
     */
    public static void upload() throws Exception {
        // id:    group1/M00/00/00/wKgBr1crVnSAbI4sAAAeV2aU4jU126.jpg
        // fastdfsBasePath = http://192.168.1.170/fastdfs
        // url:    http://192.168.1.170/fastdfs/group1/M00/00/00/wKgBr1crVnSAbI4sAAAeV2aU4jU126.jpg
        String path = System.getProperty("user.dir") + File.separatorChar + "holiday.xls";
        File file = new File(path);
        String fileid = FastDFSClient.upload(file);
        log.info("本地文件：" + path + "，上传成功！ 文件ID为：" + fileid);
    }

    /**
     * 下载
     */
    public static void download() throws Exception {
        String fileId = "group2/M00/00/00/wKjFh14mkH-ARWdrAABMAFdiPz8331.xls";
        InputStream inputStream = FastDFSClient.download("group2", fileId);
        FastDFSClient.download("group2", "group2/M00/00/00/wKjFh14mkH-ARWdrAABMAFdiPz8331.xls");
        String path = System.getProperty("user.dir") + File.separatorChar + "resources" + File.separatorChar + "holiday.xls";
        log.info(path);
        //FileUtils.copyInputStreamToFile(inputStream,  new File(path));
    }

    /**
     * 删除
     */
    public static void delete() throws Exception {
        String fileId = "group2/M00/00/00/wKjFh14myQGAdCFHAADxDvVQR9s444.jpg";
        FastDFSClient.delete("group2", fileId);
    }


    /**
     * @param args
     * @throws Exception
     */
    public static void main(String[] args) throws Exception {
        String str = "http://192.168.197.132:8000/group1/M00/00/00/wKjFhV4G1v6AE7tuAAjiaOr8RF8972.jpg";
        String host = gethost();
        if (str.indexOf(host) > -1) {
            String str2 = str.substring(host.length(), str.length() - 1);
            Matcher matcher = Pattern.compile("/").matcher(str2);
            if (matcher.find()) {
                String receiverName = str2.substring(0, matcher.start()).trim();
                delete();
            }
        }
        // upload();
        //download();
        // Thread.sleep(10000);
        //  download();
        // Thread.sleep(10000);
        //download();
        //delete();
    }







}
